package com.xmmj.common.error

import com.xmmj.baselibrary.base.activity.mvvm.BaseViewModel
import com.xmmj.baselibrary.base.activity.mvvm.IBaseErrorHandle
import com.xmmj.common.converter.ResponseError
import com.xmmj.common.R
import com.xmmj.baselibrary.base.application.BaseApplication
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLException
import javax.net.ssl.SSLHandshakeException

/**
 * 错误统一处理的工具类
 */
object ErrorHandle : IBaseErrorHandle {

    override fun handleError(throwable: Throwable, viewModel: BaseViewModel<*>) {
        viewModel.hideLoading()
        viewModel.finishRefresh()
        viewModel.finishLoadMore(false)

        //1.业务层错误（例如服务端定义的登录过期）
        if (throwable is ResponseError) {
            //登录过期
            if (throwable.code == 401) {
                viewModel.onRequest()
                return
            }
            //服务端定义的其他错误
            viewModel.toast(throwable.message)
            return
        }

        //2.协议层错误
        if (throwable is HttpException
            || throwable is ConnectException
            || throwable is UnknownHostException
            || throwable is SocketTimeoutException
            || throwable is SocketException
            || throwable is SSLException
            || throwable is SSLHandshakeException
        ) {
            viewModel.showError(
                R.drawable.ic_network,
                viewModel.applicationContext.getString(R.string.common_network_exception),
                viewModel.applicationContext.getString(R.string.common_refresh)
            )
            return
        }

        //3.其他错误（比如解析异常、空指针异常等本地异常）
        viewModel.showError(
            R.drawable.ic_error,
            throwable.toString(),
            viewModel.applicationContext.getString(R.string.common_refresh)
        )
    }
}